package com.kabuda.zhugehot200;

import java.util.HashSet;

/**
 * @author kabuda
 * @date 2025-03-16 14:36
 * @description
 */
public class t141_环形链表 {
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode2;

        System.out.println(hasCycle(listNode1));
        System.out.println(hasCycle2(listNode1));
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }


    /**
     * hashSet记录每一步
     *
     * @param head
     * @return
     */
    public static boolean hasCycle(ListNode head) {
        HashSet<ListNode> set = new HashSet<>();
        while (head != null) {
            if (set.contains(head)) {
                return true;
            }
            set.add(head);
            head = head.next;
        }
        return false;
    }

    /**
     * 快慢指针
     *
     * @param head
     * @return
     */
    public static boolean hasCycle2(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head, fast = head.next;
        while (slow != fast){
            if (fast == null || fast.next == null) {
                return false;
            }
            //一快一慢，如果有环肯定会相遇
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }


}
